import React, { useState, useRef, useEffect } from 'react';
import { callStudentAnalysis, checkAiService } from '../services/aiApi';
import { mockAiResponse } from '../utils/aiStream';
import './StudentAiAssistant.css';

interface Student {
  id: number;
  name: string;
  studentId: string;
  gender: string;
  birthDate: string;
  idCard: string;
  marketingDepartment: string;
  className: string;
  college: string;
  phone: string;
  dormBuilding: string;
  dormRoom: string;
  status: 'active' | 'suspended' | 'graduated';
  enrollmentDate: string;
}

interface StudentAiAssistantProps {
  students: Student[];
  searchTerm: string;
  searchTags: Array<{ label: string; field: string; value: string }>;
  onClose: () => void;
}

interface Message {
  id: string;
  type: 'user' | 'ai';
  content: string;
  timestamp: Date;
}

const StudentAiAssistant: React.FC<StudentAiAssistantProps> = ({
  students,
  searchTerm,
  searchTags,
  onClose
}) => {
  const [messages, setMessages] = useState<Message[]>([
    {
      id: '1',
      type: 'ai',
      content: '你好！我是学生管理AI助手。我可以帮你分析学生数据、生成统计报告、提供管理建议等。请告诉我你需要什么帮助？',
      timestamp: new Date()
    }
  ]);
  const [inputValue, setInputValue] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [isAiServiceAvailable, setIsAiServiceAvailable] = useState(false);
  const [isCheckingService, setIsCheckingService] = useState(true);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // 自动滚动到底部
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  // 检查AI服务是否可用
  useEffect(() => {
    const checkService = async () => {
      setIsCheckingService(true);
      try {
        const isAvailable = await checkAiService();
        setIsAiServiceAvailable(isAvailable);
        
        if (!isAvailable) {
          setMessages(prev => [...prev, {
            id: Date.now().toString(),
            type: 'ai',
            content: '⚠️ AI服务暂时不可用，将使用模拟数据进行演示。',
            timestamp: new Date()
          }]);
        }
      } catch (error) {
        console.error('检查AI服务失败:', error);
        setIsAiServiceAvailable(false);
      } finally {
        setIsCheckingService(false);
      }
    };

    checkService();
  }, []);

  // 生成学生数据上下文
  const generateStudentContext = () => {
    const totalStudents = students.length;
    const activeStudents = students.filter(s => s.status === 'active').length;
    const suspendedStudents = students.filter(s => s.status === 'suspended').length;
    const graduatedStudents = students.filter(s => s.status === 'graduated').length;
    
    const collegeStats = students.reduce((acc, student) => {
      acc[student.college] = (acc[student.college] || 0) + 1;
      return acc;
    }, {} as Record<string, number>);
    
    const classStats = students.reduce((acc, student) => {
      acc[student.className] = (acc[student.className] || 0) + 1;
      return acc;
    }, {} as Record<string, number>);
    
    const genderStats = students.reduce((acc, student) => {
      acc[student.gender] = (acc[student.gender] || 0) + 1;
      return acc;
    }, {} as Record<string, number>);

    const marketingStats = students.reduce((acc, student) => {
      acc[student.marketingDepartment] = (acc[student.marketingDepartment] || 0) + 1;
      return acc;
    }, {} as Record<string, number>);

    return `学生数据概览：
- 总学生数：${totalStudents}
- 在读学生：${activeStudents} (${((activeStudents/totalStudents)*100).toFixed(1)}%)
- 休学学生：${suspendedStudents} (${((suspendedStudents/totalStudents)*100).toFixed(1)}%)
- 已毕业学生：${graduatedStudents} (${((graduatedStudents/totalStudents)*100).toFixed(1)}%)
- 学院分布：${Object.entries(collegeStats).map(([college, count]) => `${college}(${count}人)`).join(', ')}
- 班级分布：${Object.entries(classStats).map(([cls, count]) => `${cls}(${count}人)`).join(', ')}
- 性别分布：${Object.entries(genderStats).map(([gender, count]) => `${gender}(${count}人)`).join(', ')}
- 市场部分布：${Object.entries(marketingStats).map(([dept, count]) => `${dept}(${count}人)`).join(', ')}
- 当前搜索条件：${searchTerm ? `关键词"${searchTerm}"` : '无'}
- 筛选标签：${searchTags.map(tag => `${tag.label}:${tag.value}`).join(', ') || '无'}`;
  };

  // 发送消息
  const sendMessage = async () => {
    if (!inputValue.trim() || isLoading) return;

    const userMessage: Message = {
      id: Date.now().toString(),
      type: 'user',
      content: inputValue.trim(),
      timestamp: new Date()
    };

    setMessages(prev => [...prev, userMessage]);
    setInputValue('');
    setIsLoading(true);

    const aiMessageId = (Date.now() + 1).toString();
    
    // 添加AI消息占位符
    setMessages(prev => [...prev, {
      id: aiMessageId,
      type: 'ai',
      content: '',
      timestamp: new Date()
    }]);

    try {
      // 根据AI服务可用性选择调用方式
      if (isAiServiceAvailable) {
        // 使用真实AI API
        await callStudentAnalysis(students, userMessage.content, {
          onChunk: (chunk: { content: string }) => {
            setMessages(prev => prev.map(msg => 
              msg.id === aiMessageId 
                ? { ...msg, content: msg.content + chunk.content }
                : msg
            ));
          },
          onComplete: () => {
            setIsLoading(false);
          },
          onError: (error: Error) => {
            console.error('AI API调用失败:', error);
            setMessages(prev => prev.map(msg => 
              msg.id === aiMessageId 
                ? { ...msg, content: msg.content + '\n\n[AI服务暂时不可用，请稍后重试]' }
                : msg
            ));
            setIsLoading(false);
          }
        });
      } else {
        // 使用模拟响应
        const contextData = generateStudentContext();
        const fullMessage = `学生管理助手，请基于以下数据回答问题：\n\n${contextData}\n\n用户问题：${userMessage.content}`;

        await mockAiResponse(fullMessage, {
          onChunk: (chunk: { content: string }) => {
            setMessages(prev => prev.map(msg => 
              msg.id === aiMessageId 
                ? { ...msg, content: msg.content + chunk.content }
                : msg
            ));
          },
          onComplete: () => {
            setIsLoading(false);
          },
          onError: (error: Error) => {
            console.error('模拟响应错误:', error);
            setMessages(prev => prev.map(msg => 
              msg.id === aiMessageId 
                ? { ...msg, content: msg.content + '\n\n[响应错误，请重试]' }
                : msg
            ));
            setIsLoading(false);
          }
        });
      }

    } catch (error) {
      console.error('发送消息失败:', error);
      setMessages(prev => prev.map(msg => 
        msg.id === aiMessageId 
          ? { ...msg, content: '抱歉，我暂时无法回答你的问题。请稍后再试。' }
          : msg
      ));
      setIsLoading(false);
    }
  };

  // 处理键盘事件
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  };

  // 快速问题模板
  const quickQuestions = [
    '分析学生数据分布情况',
    '生成学生统计报告',
    '找出需要关注的学生',
    '分析各学院学生情况',
    '提供管理建议'
  ];

  const handleQuickQuestion = (question: string) => {
    setInputValue(question);
  };

  return (
    <div className="student-ai-assistant">
      <div className="assistant-header">
        <div className="header-left">
          <h3>🤖 学生管理AI助手</h3>
          <div className="service-status">
            {isCheckingService ? (
              <span className="status-checking">检查服务中...</span>
            ) : isAiServiceAvailable ? (
              <span className="status-online">🟢 AI服务在线</span>
            ) : (
              <span className="status-offline">🔴 使用模拟数据</span>
            )}
          </div>
        </div>
        <button className="close-btn" onClick={onClose}>×</button>
      </div>

      <div className="assistant-context">
        <h4>当前数据概览：</h4>
        <pre>{generateStudentContext()}</pre>
      </div>

      <div className="quick-questions">
        <h4>快速问题：</h4>
        <div className="question-tags">
          {quickQuestions.map((question, index) => (
            <button
              key={index}
              className="question-tag"
              onClick={() => handleQuickQuestion(question)}
            >
              {question}
            </button>
          ))}
        </div>
      </div>

      <div className="assistant-messages">
        {messages.map((message) => (
          <div key={message.id} className={`message ${message.type}`}>
            <div className="message-avatar">
              {message.type === 'user' ? '👤' : '🤖'}
            </div>
            <div className="message-content">
              <div className="message-text">
                {message.content}
              </div>
              <div className="message-time">
                {message.timestamp.toLocaleTimeString()}
              </div>
            </div>
          </div>
        ))}
        {isLoading && (
          <div className="message ai">
            <div className="message-avatar">🤖</div>
            <div className="message-content">
              <div className="typing-indicator">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          </div>
        )}
        <div ref={messagesEndRef} />
      </div>

      <div className="assistant-input">
        <textarea
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
          onKeyPress={handleKeyPress}
          placeholder="输入你的问题..."
          disabled={isLoading}
          rows={3}
        />
        <button 
          onClick={sendMessage} 
          disabled={!inputValue.trim() || isLoading}
          className="send-btn"
        >
          {isLoading ? '发送中...' : '发送'}
        </button>
      </div>
    </div>
  );
};

export default StudentAiAssistant;
